import json
import os
import tempfile

from dotenv import load_dotenv
from e2b_code_interpreter import Sandbox
from flask import Flask, jsonify, render_template_string, request
from openai import OpenAI

# 加载环境变量
load_dotenv()

# 初始化API客户端
openai_client = OpenAI(
    api_key=os.getenv("OPENAI_API_KEY"),
    base_url=os.getenv("OPENAI_BASE_URL")
)

# 创建Flask应用
app = Flask(__name__)

# 默认HTML模板
DEFAULT_HTML = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI网页生成器</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
            color: #333;
        }
        h1 {
            color: #2c3e50;
            text-align: center;
        }
        .container {
            border: 1px solid #ddd;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        form {
            margin-top: 20px;
        }
        input, textarea {
            width: 100%;
            padding: 8px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #2980b9;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>AI网页生成器</h1>
        <form id="generateForm">
            <textarea id="prompt" rows="4" placeholder="描述你想要生成的网页内容..." required>文字统计器，用户粘贴一段文本后，统计文本字数</textarea>
            <button type="submit">生成网页</button>
        </form>
        <div id="result" class="result"></div>
    </div>
    

    <script>
        document.getElementById('generateForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const prompt = document.getElementById('prompt').value;
            const resultDiv = document.getElementById('result');
            
            resultDiv.innerHTML = '生成中，请稍候...';
            
            try {
                const response = await fetch('/generate', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({prompt: prompt})
                });
                
                const data = await response.json();
                
                if (data.html) {
                    resultDiv.innerHTML = '生成成功! 下方显示生成的网页:';

                    // 部署到E2B的响应
                    if (data.e2b_url) {
                        resultDiv.innerHTML += `<br><br>已部署到E2B! <a href="${data.e2b_url}" target="_blank">点击访问</a>`;
                    } else {
                        resultDiv.innerHTML += `<br>部署失败: ${data.error}`;
                    }
                } else {
                    resultDiv.innerHTML = '生成失败: ' + data.error;
                }
            } catch (error) {
                resultDiv.innerHTML = '发生错误: ' + error;
            }
        });
    </script>
</body>
</html>
"""

@app.route('/')
def index():
    return render_template_string(DEFAULT_HTML)

@app.route('/generate', methods=['POST'])
def generate():
    try:
        data = request.json
        prompt = data.get('prompt', '')
        
        if not prompt:
            return jsonify({'error': '提示词不能为空'}), 400
        
        # 使用OpenAI生成HTML
        response = openai_client.chat.completions.create(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "你是一位专业的Web开发人员。用户会提供要求，你需要生成符合要求的HTML页面。只返回完整的HTML代码，不要包含其他解释性文字。"},
                {"role": "user", "content": f"根据以下描述生成一个HTML页面: {prompt}。只返回HTML代码，不要有其他解释。确保包含样式和必要的JavaScript以使页面功能完整。"}
            ]
        )
        
        # 提取生成的HTML
        html_content = response.choices[0].message.content
        
        # 移除可能的Markdown代码块标记
        if html_content.startswith("```html"):
            html_content = html_content[7:]
        if html_content.startswith("```"):
            html_content = html_content[3:]
        if html_content.endswith("```"):
            html_content = html_content[:-3]
            
        # 将文件在本地保存一份用作测试
        with open("test.html", "w") as f:
            f.write(html_content)
        
        # 将生成的HTML部署到E2B
        e2b_url = deploy_html_to_e2b(html_content)
        
        return jsonify({'html': html_content, 'e2b_url': e2b_url})
    
    except Exception as e:
        return jsonify({'error': str(e)}), 500

def deploy_html_to_e2b(html_content):
    """将生成的HTML上传到E2B sandbox并返回公共URL"""
    try:
        # 创建一个新的sandbox实例
        sandbox = Sandbox()
        print(sandbox)
        sandbox.set_timeout(60)
        
        # 创建临时文件存储HTML内容
        with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False) as temp_file:
            temp_file.write(html_content)
            temp_file_path = temp_file.name
        
        # 上传HTML文件到sandbox
        target_path = "/home/user/index.html"
        with open(temp_file_path, "rb") as file:
            sandbox.files.write(target_path, file)        
        
        # 启动Web服务器
        process = sandbox.commands.run("cd /home/user && python -m http.server 3000", background=True)
        host = sandbox.get_host(3000)
        print(host)
        public_url = f"https://{host}"
        
        print(f"生成的网页已部署，公共URL: {public_url}")
        return public_url
    
    except Exception as e:
        print(f"部署失败: {str(e)}")
        return None

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5005)
